package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.util.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    //文件存到哪里
    public static final String UPLOAD_DIR="D:/upload/";

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /***
     * 文件上传
     * 1、文件存到哪里
     * 2、文件存的时候，名字是什么
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传:{}",file);

        //文件名字(存储的文件名)  1.jpg->处理（随机数.jpg | UUID.jpg）
        //1）获取文件名  1.jpg
        String fileName = file.getOriginalFilename();

        //2）获取文件后缀  jpg
        //fileName.lastIndexOf(".")  当前字符串最后一个点的索引
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());

        //3）生成随机数/UUID作为存储文件的名字   UUID/随机数 + "."+jpg
        String fullName = UUID.randomUUID().toString().replace("-","")+suffix;

        //4）存储文件到指定目录
        //file.transferTo(new File(UPLOAD_DIR,fullName));
        String url = aliyunOSSOperator.upload(file.getBytes(), fullName);
        return Result.success(url);
    }

    public static void main(String[] args) {
        String fileName = "88812.3.jpg";
        System.out.println(fileName.lastIndexOf("."));
        String sub = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println(sub);

        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println(UUID.randomUUID().toString().replace("-",""));
        System.out.println(UUID.randomUUID().toString().replace("-",""));
    }

}
